package net.keebook.webapp.validator;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.component.UIComponent;
import javax.faces.component.UIInput;
import javax.faces.context.FacesContext;
import javax.faces.validator.Validator;
import javax.faces.validator.ValidatorException;
import javax.inject.Inject;

import net.keebook.webapp.dao.UserDao;
import net.keebook.webapp.entity.User;
import net.keebook.webapp.util.MessageBundle;

@ManagedBean
@RequestScoped
public class UsernameValidator implements Validator {
	@Inject
	private UserDao userDao;
	
	@Override
	public void validate(FacesContext context, UIComponent component, Object value) throws ValidatorException {
		String username = (String)value;
		
		// Check for invalid characters
		Pattern p = Pattern.compile("^[a-zA-Z0-9_\\-@\\.\\:]+$");
		Matcher m = p.matcher(username);
		if (!m.find()) {
			((UIInput)component).setValid(false);
			context.addMessage(component.getClientId(context), new FacesMessage(MessageBundle.get().getString("error.alphaNumericOnly")));
			return;
		}
		
		// Check if user with same name already exists
		User user = getUserDao().getUserByUsername(username);
		if (user != null) {
			// ...but only throw error if user id differs
			UIInput hiddenUserIdField = (UIInput)context.getViewRoot().findComponent("addUserForm:userId");
			if ((hiddenUserIdField == null) || (!user.getExposableId().equals((String)hiddenUserIdField.getValue()))) {
				((UIInput)component).setValid(false);
				context.addMessage(component.getClientId(context), new FacesMessage(MessageBundle.get().getString("error.accountExists")));
			}
		}
	}

	public UserDao getUserDao() {
		return userDao;
	}

	public void setUserDao(UserDao userDao) {
		this.userDao = userDao;
	}
}
